<?php
/**
 * Created by PhpStorm.
 * User: eugene
 * Date: 2017/8/7
 * Time: 17:09
 */

namespace App\Transformers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;

/**
 * Class Transformer
 * dingo的转换器简单版本，统一接口格式
 * @package App\Transformers
 */
abstract class Transformer
{
    protected $transformer='transform';
    protected $emptyItemer='emptyItem';

    public function setTransformer($transformer)
    {
        $this->transformer=$transformer;
        return $this;
    }

    public function setEmptyItem($funcName)
    {
        $this->emptyItemer=$funcName;
        return $this;
    }

    public function listData($data)
    {
        if(!($data instanceof Collection)){
            //报错机制
            return $this->{$this->emptyItemer}();
        }
        return $data->transform(function($item){
            return $this->{$this->transformer}($item);
        })->all();
    }

    public function singleData($data)
    {
        if(!($data instanceof Model)){
            //报错机制
            return $this->emptyItem();
        }
        return collect($this->{$this->transformer}($data))->all();
    }

    protected function transform($item){}

    //对象为空时如何处理
    protected function emptyItem()
    {
        return [];
    }
}